package cn.fboost.mtos.service.impl;

import cn.fboost.mtos.dto.Response;
import cn.fboost.mtos.dto.internal.Session;
import cn.fboost.mtos.dto.request.*;
import cn.fboost.mtos.dto.response.PageResponse;
import cn.fboost.mtos.entity.Admin;
import cn.fboost.mtos.entity.User;
import cn.fboost.mtos.mapper.AdminMapper;
import cn.fboost.mtos.mapper.UserMapper;
import cn.fboost.mtos.service.UserService;
import cn.fboost.mtos.util.ContextHolderUtil;
import cn.fboost.mtos.util.EncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final AdminMapper adminMapper;

    public UserServiceImpl(UserMapper userMapper, AdminMapper adminMapper) {
        this.userMapper = userMapper;
        this.adminMapper = adminMapper;
    }

    @Override
    public Response updateUserProfile(UserProfileUpdateRequest request) {
        Session session = ContextHolderUtil.getCurrentSession();

        if (session.getRole() == Session.Role.ADMIN) {
            // 管理员修改用户信息时，必须传入正确的用户ID
            if (request.getId() == null || request.getId() <= 0) {
                return Response.builder().failure().msg("参数错误").build();
            }
        } else {
            // 普通用户只能修改自己的信息
            request.setId(session.getId());
        }

        User user = new User();
        user.setId(request.getId());
        user.setNickname(request.getNickname());

        if (userMapper.update(user) == 0) {
            return Response.builder().failure().msg("修改失败").build();
        }

        return Response.builder().success().msg("修改成功").build();
    }

    @Override
    public Response userList(PageRequest request) {
        int total = userMapper.count();
        List<User> list = userMapper.list(request.getPageOffset());

        PageResponse resp = new PageResponse();
        resp.setTotal(total);
        resp.setList(list);
        return Response.builder().success().msg("获取成功").data(resp).build();
    }

    @Override
    public Response createAdmin(AdminCreateRequest request) {
        Session session = ContextHolderUtil.getCurrentSession();
        // 只有超级管理员才能创建管理员
        if (session.getId() != 1) {
            return Response.builder().failure().msg("没有权限").build();
        }

        // 密码强度检查
        Response response = EncryptUtil.checkStrength(request.getPassword());
        if (!response.isSuccess()) {
            return response;
        }

        Admin admin = new Admin();
        admin.setUsername(request.getUsername());
        admin.setPassword(EncryptUtil.encryptPassword(request.getPassword()));
        if (adminMapper.create(admin) == 0) {
            return Response.builder().failure().msg("创建失败").build();
        }

        return Response.builder().success().msg("创建成功").build();
    }

    @Override
    public Response deleteAdmin(AminDeleteRequest request) {
        Session session = ContextHolderUtil.getCurrentSession();
        // 只有超级管理员才能删除管理员
        if (session.getId() != 1) {
            return Response.builder().failure().msg("没有权限").build();
        }

        if (Objects.equals(request.getId(), session.getId())) {
            return Response.builder().failure().msg("不能删除自己").build();
        }

        if (adminMapper.deleteById(request.getId()) == 0) {
            return Response.builder().failure().msg("删除失败").build();
        }

        return Response.builder().success().msg("删除成功").build();
    }

    @Override
    public Response updateAdminProfile(AdminProfileUpdateRequest request) {
        Session session = ContextHolderUtil.getCurrentSession();
        // 只有超级管理员才能修改其他管理员资料，普通管理员只能修改自己的资料
        if (session.getId() != 1 && !Objects.equals(request.getId(), session.getId())) {
            return Response.builder().failure().msg("没有权限").build();
        }

        // 如果提交了密码，则检查密码强度
        if (request.getPassword() != null) {
            Response response = EncryptUtil.checkStrength(request.getPassword());
            if (!response.isSuccess()) {
                return response;
            }
        }

        Admin admin = new Admin();
        admin.setId(request.getId());
        admin.setUsername(request.getUsername());
        admin.setPassword(EncryptUtil.encryptPassword(request.getPassword()));
        if (adminMapper.update(admin) == 0) {
            return Response.builder().failure().msg("修改失败").build();
        }

        return Response.builder().success().msg("修改成功").build();
    }
}
